/**
 * 
 */
package com.itinsys.enma.service.impl;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.itinsys.enma.domain.Planning;
import com.itinsys.enma.domain.PlanningReservation;
import com.itinsys.enma.domain.Status;
import com.itinsys.enma.manager.PlanningManager;
import com.itinsys.enma.manager.ReservationManager;
import com.itinsys.enma.service.ReservationDateChecker;

/**
 * @author pferraz
 *
 */
public class ReservationDateCheckerImpl implements ReservationDateChecker{

	private static Logger logger = Logger.getLogger("service");
	
	@Autowired
	private ReservationManager reservationManager;
	@Autowired
	private PlanningManager planningManager;

	@Override
	public void checkReservationDates() {
		logger.info("Inicia chequeo de reservas");
		List<PlanningReservation> reservationToStart=reservationManager.getReservationsToStart(new Date(new java.util.Date().getTime()).toString());
		for(PlanningReservation res:reservationToStart){
			res.setActive(true);
			reservationManager.directUpdate(res);
		}
		Map<Integer,Planning> planns=new HashMap<Integer, Planning>();
		List<PlanningReservation> reservationToEnd=reservationManager.getReservationsToEnd(new Date(new java.util.Date().getTime()).toString());
		for(PlanningReservation res:reservationToEnd){
			res.setActive(false);
			reservationManager.directUpdate(res);
			if(!planns.containsKey(res.getPlanning().getId()))
				planns.put(res.getPlanning().getId(), res.getPlanning());
				
		}
		
		for(Integer key:planns.keySet()){
			if(reservationManager.allReservationsDisable(key)){
				planns.get(key).setStatus(Status.ENDED.toString());
				planningManager.directUpdate(planns.get(key));
			}			
		}
		
		logger.info("Finaliza chequeo de reservas ");
		
	}
	
	
}
